const express = require('express');
const router = express.Router();
const Airship = require("../models/Airship");
const dayjs = require('dayjs');
const axios = require('axios');
const { createResponse } = require('../utils/response');
const Sequelize = require("sequelize");

// 新的接口 URL
const otherApiUrl = 'https://16894907.com/api/pks/queryHistoryDataForDsdx.do?lotCode=10037';

// 定义获取数据并保存的函数
const fetchAndSaveData = async () => {
    try {
        //检查当天是否有数据
        const count = await Airship.count({
            where: {
                gernerate_date: {
                    [Sequelize.Op.between]: [
                        dayjs().startOf('day').toDate(),
                        dayjs().endOf('day').toDate()
                    ],
                }
            }
        });
        if (count === 0) {
            await initializeRankingData();
        }


        const response = await axios.get(otherApiUrl);
        const { result } = response.data;
        const curDayList = result.data[0].list;
        if (Array.isArray(curDayList)) {
            for (const item of curDayList) {
                //通过排名和日期查询
                const rankData = await Airship.findOne({
                    where: {
                        rank: item.rank, gernerate_date: {
                            [Sequelize.Op.between]: [
                                dayjs().startOf('day').toDate(),
                                dayjs().endOf('day').toDate()
                            ],
                        }
                    }
                });
                if (!rankData) {
                    console.error(`未找到排名为 ${item.rank} 的数据`);
                    continue;
                }
                //大小
                let size_max_diff, size_max_diff_time;
                //绝对值
                const size_diff = Math.abs(item.bigCount - item.smallCount);
                if (rankData.size_max_diff < size_diff) {
                    size_max_diff = size_diff
                    size_max_diff_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
                } else {
                    size_max_diff = rankData.size_max_diff;
                    size_max_diff_time = rankData.size_max_diff_time;
                }

                //单双
                let single_double_max_diff, single_double_max_diff_time;
                const single_double_diff = Math.abs(item.singleCount - item.doubleCount);
                if (rankData.single_double_max_diff < single_double_diff) {
                    single_double_max_diff = single_double_diff;
                    single_double_max_diff_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
                } else {
                    single_double_max_diff = rankData.single_double_max_diff;
                    single_double_max_diff_time = rankData.single_double_max_diff_time;
                }


                rankData.update(
                    {
                        big_value: item.bigCount,
                        small_value: item.smallCount,
                        size_diff,
                        size_max_diff,
                        size_max_diff_time,
                        //单双
                        single_value: item.singleCount,
                        double_value: item.doubleCount,
                        single_double_max_diff,
                        single_double_diff,
                        single_double_max_diff_time,
                        gernerate_date: dayjs().format('YYYY-MM-DD')
                    }
                );

            }
        }
    } catch (error) {
        console.error('获取数据或保存数据时出错:', error);
    }
};

// 每隔一段时间执行一次
const intervalTime = 2 * 1000;
setInterval(fetchAndSaveData, intervalTime);

// 初始化排名数据
const initializeRankingData = async () => {
    for (let i = 1; i <= 10; i++) {
        try {
            await Airship.create({ rank: i, size_max_diff: 0, single_double_max_diff: 0, gernerate_date: dayjs().format('YYYY-MM-DD') });
        } catch (error) {
            console.error(`创建排名为 ${i} 的数据时出错:`, error);
        }
    }
    console.log('排名数据初始化完成');
    return Promise.resolve();
};

router.post('/getAll', async (req, res) => {
    try {

        const { gernerateDate } = req.body;
        //通过日期查询
        const data = await Airship.findAll({
            where: {
                gernerate_date: {
                    [Sequelize.Op.between]: [
                        dayjs(gernerateDate).startOf('day').toDate(),
                        dayjs(gernerateDate).endOf('day').toDate()
                    ]
                },
            },
        });

        res.json(createResponse(200, 'success', data));
    } catch (error) {
        res.status(500).json({ error: '获取数据失败' });
    }
})

module.exports = router;